import React, { StrictMode, useEffect, useState } from 'react';
import { Tabs, message, Select, Switch, Table, Form, Input, Spin, Modal } from 'antd';
import { OpenAIOutlined } from '@ant-design/icons'
import AppConfig from '../../config/config';
import '../../css/styles.css'
import MyTable from './myTable';

const ComponmentTypeList = ({ uploadInfo, setUploadInfo, setCurrent }) => {

    const [activeTab, setActiveTab] = useState('1');
    const [childrenActiveTab, setChildrenActiveTab] = useState('1');
    const [componData, setComponData] = useState([]);
    const [options, setOptions] = useState([])
    const [selectShowList, setSelectShowList] = useState([{}])
    const [loading, setLoading] = useState(true);
    /**
    * 初始化数据
    */
    useEffect(() => {
        getInfo()
        getAllType()
    }, [])

    /**
     * 获取所有数据
     */
    const getInfo = () => {
        fetch(API_URL + '/importTable/getTableElements', {
            method: 'post',
            body: JSON.stringify(uploadInfo),
            headers: { 'Content-Type': 'application/json' }
        })
            .then((res) => res.json())
            .then((data) => {
                if (data) {
                    //将返回的元素设置进uploadinfo
                    setUploadInfo({ ...uploadInfo, tablesElements: data })
                    //生成sheet页数据，按sheet页分组
                    const result = Object.entries(data.reduce((acc, obj) => {
                        const { tableName, canvasName, elements, maxCols } = obj;
                        if (!acc[tableName]) {
                            acc[tableName] = [];
                        }
                        acc[tableName].push({
                            ...obj,
                            //处理elements中的数据，按行号分组
                            elements: Object.values(elements.reduce((acc, curr) => {
                                const { rowNum, colNum, aiFlag } = curr;
                                if (!acc[rowNum]) {
                                    acc[rowNum] = { tableName, canvasName, rowNum, colNum, maxCols, aiFlag, rowElements: [] };
                                }
                                acc[rowNum].rowElements.push(curr);

                                return acc;
                            }, {}))
                        });

                        return acc;
                    }, {})).map(([tableName, table]) => ({ tableName, table }));
                    // console.log(result);
                    let selectShowList = []
                    //设置选项数组
                    data.forEach(({ canvasName, tableName, elements }) => {
                        elements.forEach(({ rowNum, colNum, dataType, aiFlag }) => {
                            let selectShowType = {}
                            if (dataType == 'SELECT') {
                                selectShowType = {
                                    canvasName, tableName,
                                    index: rowNum + "_" + colNum,
                                    dataType,
                                    aiFlag,
                                    type: true
                                }
                            } else {
                                selectShowType = {
                                    canvasName, tableName,
                                    index: rowNum + "_" + colNum,
                                    dataType,
                                    aiFlag,
                                    type: false
                                }
                            }

                            selectShowList.push(selectShowType)

                        })
                    })
                    setSelectShowList(selectShowList)
                    setComponData(result)
                    setLoading(false)
                }
            })
            .catch(e => {
                message.error("获取数据错误！错误：" + e);
                setCurrent(0)
            })
    }

    /**
     * 获取组件类型
     */
    const getAllType = () => {
        fetch(API_URL + '/importTable/getAllType', {
            method: 'get'
        })
            .then((res) => res.json())
            .then((response) => {
                console.log(response);
                setOptions(Object.keys(response).map(key => {
                    return { value: key, label: response[key] };
                }))
            })
            .catch(e => {
                message.error("获取组件类型错误！错误：" + e);
            })
    }

    /**
     * 
     * 页签
     * 
     */

    /**
     * 页签切换
     * @param {*} key 
     */
    const handleTabChange = (key) => {
        setActiveTab(key);
    };

    const getItems = () => {
        let resultItems = []
        
        componData.map(({ tableName, table }) => {
            let childrenItems = [];
            table.forEach(e => {
                let { canvasName, elements, maxCols } = e;
                let childrenItem = {
                    key: canvasName,
                    label: canvasName,
                    children:(
                        <StrictMode key={canvasName}>
                            <h2>{canvasName}</h2>
    
                            <div className='Mytable'>
                                <MyTable
    
                                    bordered
    
                                    dataSource={getExcelData(elements)}
                                    columns={getExcelColumn(maxCols)}
                                    tableConfig={{
                                        key: canvasName,
                                        pagination: false,
                                        // scroll: { x: true } // 启用水平滚动条
                                        scroll: {
                                            x: true,
    
                                        },
    
                                        // antd site header height
                                        sticky: {
                                            offsetHeader: 64,
                                        }
    
                                    }}
                                />
                            </div>
                        </StrictMode>
                    )
                }
                childrenItems.push(childrenItem)
            })

            let fatherItem = {
                key: tableName,
                label: tableName,
                children: (
                    <Tabs
                        defaultActiveKey={childrenActiveTab}
                        items={childrenItems}
                        onChange={() => {
                            setChildrenActiveTab(tableName)
                        }} />
                )
            }
            resultItems.push(fatherItem)
        });
        return resultItems;
    }


    /**
     * 
     * 表格
     * 
     */


    /**
     * 获取表格列
     * @param {*} number 
     */
    const getExcelColumn = (number) => {
        const columns = [
            {
                key: 'rowNum',
                title: '行号',
                dataIndex: 'key',
                width: 80,
                fixed: 'left',

            },
        ];
        for (let index = 1; index <= number; index++) {
            let columnName = getExcelColumnName(index)
            let column = {
                title: columnName,
                dataIndex: columnName,
                width: 200,
                render: renderCell,
                key: columnName

            }
            columns.push(column)
        }
        return columns;
    }

    /**
     * 渲染单元格
     * @param {*} value 
     * @param {*} row 
     * @param {*} rowIndex 
     * @param {*} colIndex 
     * @returns value
     */
    const renderCell = (value, row, rowIndex, colIndex) => {
        const { rows, cols, dataType, rowNum, colNum, canvasName, tableName, aiFlag, } = value || {};
        const defaultOptions = value ? value.options : null;
        let props = {}
        let children = ''
        //单元格元素
        if (dataType && value) {
            let textValue = value.value
            if (dataType == 'BLANK' || dataType == 'PARAGRAPH') {
                children = textValue
            } else {
                children = (
                    <div>
                        {
                            aiFlag ? <div style={{ color: '#FF0000' }}><OpenAIOutlined twoToneColor='#FF0000' />由AI识别</div> : null
                        }

                        <Form>
                            <Form.Item
                                label='组件内容'
                                name="componmentTitle"
                            >
                                <Input
                                    defaultValue={textValue}
                                    onChange={(value) => componmentTitleChange(tableName, canvasName, rowNum, colNum, value)}
                                // disabled={true}
                                />
                            </Form.Item>
                            <Form.Item
                                label='组件类型'
                                name="componmentType"
                            >
                                <Select
                                    style={{ width: '100px' }}
                                    defaultValue={dataType}
                                    options={options}
                                    onChange={(value) => componmentTypeChange(tableName, canvasName, rowNum, colNum, value)}
                                />
                            </Form.Item>
                            {

                                (
                                    selectShowList.find(e => e.index == rowNum + '_' + colNum && e.canvasName == canvasName && e.tableName == tableName)?.type
                                )
                                    ?
                                    <Form.Item
                                        label='选项（以"/"分隔）'
                                        name="selects"
                                    >
                                        <Input
                                            defaultValue={defaultOptions}
                                            onChange={(value) => selectOptionsChange(tableName, canvasName, rowNum, colNum, value)} />
                                    </Form.Item>
                                    : null
                            }
                        </Form>

                    </div>
                )

            }
        } else {
            children = value ? value.value : ''

        }
        // 设置合并单元格的行数和列数
        if (rows && cols) {
            props = {
                rowSpan: rows,
                colSpan: cols,
            }
        } else {
            // 如果不是合并单元格，则设置为空对象
            props = {
                rowSpan: 0,
                colSpan: 0,
            }
        }

        const obj = {
            children,
            props
        };
        return obj;
    };

    /**
     * 单元格中，修改元素组件后的事件
     * @param {*} rowNum 
     * @param {*} colNum 
     * @param {*} value 
     */
    const componmentTypeChange = (tableName, canvasName, rowNum, colNum, value) => {
        //如果设置的是选项，添加选项节点
        let type = false;
        if (value == 'SELECT') {
            type = true
        }
        setSelectShowList(selectShowList.map(e => {
            if (e.tableName == tableName && e.canvasName == canvasName && e.index == rowNum + '_' + colNum) {
                e.type = type
            }
            return e;
        })
        )
        //修改选项类型数据
        let { tablesElements } = uploadInfo;
        let newTablesElements = tablesElements.map(te => {
            if (te.canvasName == canvasName && te.tableName == tableName) {
                let { elements } = te;
                let newElements = elements.map(e => {
                    if (e.rowNum == rowNum && e.colNum == colNum) {
                        e.dataType = value
                    }
                    return e
                })
                te.elements = newElements;
            }
            return te
        })
        uploadInfo.tablesElements = newTablesElements;
        setUploadInfo(uploadInfo);
    };
    /**
     * 组件文本修改
     * @param {*} tableName 
     * @param {*} canvasName 
     * @param {*} rowNum 
     * @param {*} colNum 
     * @param {*} value 
     */
    const componmentTitleChange = (tableName, canvasName, rowNum, colNum, value) => {

        const titleValue = value.target.value;
        //修改选项类型数据
        let { tablesElements } = uploadInfo;
        let newTablesElements = tablesElements.map(te => {
            if (te.canvasName == canvasName && te.tableName == tableName) {
                let { elements } = te;
                let newElements = elements.map(e => {
                    if (e.rowNum == rowNum && e.colNum == colNum) {
                        e.title = titleValue
                    }
                    return e
                })
                te.elements = newElements;
            }
            return te
        })
        uploadInfo.tablesElements = newTablesElements;
        setUploadInfo(uploadInfo);
    }
    /**
     * 选项数据修改
     * @param {*} tableName 
     * @param {*} canvasName 
     * @param {*} rowNum 
     * @param {*} colNum 
     * @param {*} value 
     */
    const selectOptionsChange = (tableName, canvasName, rowNum, colNum, value) => {
        const optionsValue = value.target.value;

        //修改options
        let { tablesElements } = uploadInfo;
        let newTablesElements = tablesElements.map(te => {
            if (te.canvasName == canvasName && te.tableName == tableName) {
                let { elements } = te;
                let newElements = elements.map(e => {
                    if (e.rowNum == rowNum && e.colNum == colNum) {
                        e.options = optionsValue
                    }
                    return e
                })
                te.elements = newElements;
            }
            return te
        })
        uploadInfo.tablesElements = newTablesElements;
        setUploadInfo(uploadInfo);
    }

    /**
     * 获取单元格列号
     * @param {*} number 
     * @returns 
     */
    const getExcelColumnName = (number) => {
        if (!number || number < 1) {
            return;
        }
        let columnName = '';
        while (number > 0) {
            let remainder = (number - 1) % 26;
            columnName = String.fromCharCode(65 + remainder) + columnName;
            number = Math.floor((number - 1) / 26);
        }
        if (!columnName) {
            console.log(number);
        }
        return columnName;
    };


    /**
     * 获取excel数据
     * @param {*} elements 
     * @returns 
     */
    const getExcelData = (elements) => {
        if (!elements || elements.length == 0) {
            return
        }

        //获取合并的单元格
        let mergedCells = []
        elements.forEach(data => {
            let { rowElements } = data;
            rowElements.forEach(e => {
                if (e.mergeFlag) {
                    mergedCells.push(e)
                }
            })
        })

        let excelDatas = [];
        elements.forEach(e => {
            let { rowNum, maxCols, rowElements, canvasName, tableName } = e;
            let data = {
                key: rowNum + 1,
                maxCols,
            }

            rowElements.forEach(e => {
                let { dataType, title, mergeFlag, colNum, aiFlag, options } = e;
                let colNumName = getExcelColumnName(colNum + 1)
                if (mergeFlag) {
                    let { firstRow, firstCol, lastRow, lastCol } = e
                    data[colNumName] = {
                        canvasName, tableName,
                        value: title,
                        rowNum,
                        colNum,
                        mergeFlag,
                        dataType,
                        aiFlag,
                        options,
                        rows: lastRow - firstRow + 1,
                        cols: lastCol - firstCol + 1,
                    }
                } else {
                    data[colNumName] = {
                        canvasName, tableName,
                        value: title,
                        rowNum,
                        colNum,
                        dataType,
                        aiFlag,
                        mergeFlag,
                        options,
                        rows: 1,
                        cols: 1

                    }
                }

            })
            //设置空白行
            for (let index = 0; index < maxCols; index++) {
                let colNumName = getExcelColumnName(index + 1)

                //判断是否为被合并的单元格，如果不是则为空白
                if (!isMergedCell(rowNum, index, mergedCells) && !data[colNumName]) {
                    let colName = getExcelColumnName(index);
                    let e = data[colName];
                    if (!e) {
                        data[colName] = {
                            value: null, dataType: "BLANK", rows: 1, cols: 1
                        }
                    }
                }

            }


            excelDatas.push(data)

        })

        return excelDatas
    }

    /**
     * 判断是否为合并单元格
     * @param {*} rowIndex 
     * @param {*} colIndex 
     * @param {*} mergedCells 
     * @returns 
     */
    const isMergedCell = (rowIndex, colIndex, mergedCells) => {
        for (const cell of mergedCells) {
            const { firstRow, lastRow, firstCol, lastCol } = cell;
            if (rowIndex >= firstRow && rowIndex <= lastRow && colIndex >= firstCol && colIndex <= lastCol) {
                return true;
            }
        }
        return false;
    };


    return (
        <div>
            <Spin spinning={loading} size="large">
                <Tabs
                    defaultActiveKey={activeTab}
                    items={getItems()}
                    onChange={handleTabChange}
                />

            </Spin>
            {/* 加载时的模态框 */}
            <Modal open={loading} footer={null} closable={false}>
                <OpenAIOutlined />调用AI模型生成组件中...
            </Modal>
        </div>
    )
}
export default ComponmentTypeList;